package diona.auth

//import com.dropbox.client.Authenticator
import diona.model.User
import net.liftweb.http._
import net.liftweb.actor.LiftActor
import net.liftweb.common.{Empty, Box}

/**
 * User: anton
 * Date: 21.04.11 22:45
 */
object DropboxAuthorizer extends Authorizer with LiftActor with ListenerManager
{
  protected def createUpdate = "Registered"

  override def lowPriority =
  {
    case msg: DropboxAuthorization => {
      updateListeners(msg)
    }
  }

  val authAddress = "auth" :: "dropbox" :: Nil

  @volatile var processToken: LiftRules.DispatchPF = {
    case Req("auth" :: "dropbox" :: Nil, _, _) => () => processAuthorization()
  }

  @volatile var redirectToAuthorization: LiftRules.DispatchPF = {
    case Req("auth" :: "redirect" :: "dropbox" :: Nil, _, _) => () => S.redirectTo(buildRedirectUrl());
  }

  //lazy val config = Authenticator.loadConfig(getClass.getResource("/dropboxConfig.json").getPath)

  def buildRedirectUrl(): String =
  {
//    val auth = new Authenticator(config)
//    val url = auth.retrieveRequestToken(backRedirectUrl)
//    CurrentDropboxAuth(auth)
//    url
    null
  }

//  def auth(dbAuth: DropboxAuth): Authenticator =
//  {
//    val auth = new Authenticator(config)
//    auth.consumer.setTokenWithSecret(dbAuth.authToken.get, dbAuth.secret.get)
//    auth
//  }

  private def processAuthorization(): Box[LiftResponse] =
  {
//    for {
//      newToken <- S.param("oauth_token") ?~ "oauth token not defined" ~> 400
//      uid <- S.param("uid") ?~ "uid not defined" ~> 400
//      user <- User.currentUser ?~ "user not defined" ~> 400
//    } yield {
//      val auth = CurrentDropboxAuth.get
//      auth.retrieveAccessToken("")
//      val secret = auth.getTokenSecret
//      val token = auth.getTokenKey
//      val currentToken: Option[DropboxAuth] = DropboxAuth.byUser(user)
//      val newAuth = currentToken match {
//        case None => DropboxAuth.save(token, secret, uid, user)
//        case _ => DropboxAuth.update(token, secret, uid, user)
//      }
//      CurrentDropboxAuth.remove()
//      DropboxAuthorizer ! DropboxAuthorization(user)
//      createCloseWindowResponse()
//    }
    Empty
  }

  //private object CurrentDropboxAuth extends SessionVar[Authenticator](null)

}

case class DropboxAuthorization(user: User)
